<template>
  <div class="tourist-list-container">
    <el-card shadow="never" class="mb-5 border-box">
    <div class="filter-section">
      <div class="left-section">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索游客联系方式"
            class="search-input"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </div>
      </div>
    </div>
  </el-card>
    <div class="page-content tourist-list">
      <el-table
        v-loading="isLoading"
        :data="touristList"
        class="w-full"
        v-if="!showEmpty"
        height="calc(100vh - 328px)"
      >
        <el-table-column prop="userName" label="人员姓名" min-width="150" />
        <el-table-column prop="userSex" label="性别" min-width="80">
          <template #default="scope">
            <span v-if="scope.row.userSex === 1">男</span>
            <span v-else-if="scope.row.userSex === 2">女</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="userPhone" label="联系方式" min-width="120" />

        <el-table-column prop="dateBirth" label="出生日期" min-width="120">
          <template #default="scope">
            {{ scope.row.dateBirth ? useDateFormat(scope.row.dateBirth, 'YYYY-MM-DD') : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="gzhOpenid" label="公众号openid" min-width="180" />
        <el-table-column prop="unionId" label="微信唯一id" min-width="150" />
        <el-table-column fixed="right" label="操作" width="160px">
          <template #default="scope">
            <el-row>
              <el-button   
                type="primary"
                text
                size="small" 
                link
                @click="showDetailDialog(scope.row)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <!-- <el-button type="primary" link @click="showDialog('edit',scope.row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button> -->
            </el-row>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <div class="flex justify-center h-[calc(100vh-328px)]" v-if="showEmpty">
        <el-empty description="暂无游客数据" />
      </div>

      <!-- 分页器 -->
      <div class="flex justify-center mt-5">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :hide-on-single-page="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 编辑 -->
      <el-dialog v-model="dialogVisible" title="编辑游客信息" width="50%">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="人员姓名" prop="userName">
            <el-input v-model="form.userName" />
          </el-form-item>
          <el-form-item label="性别" prop="userSex">
            <el-radio-group v-model="form.userSex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号" prop="userPhone">
            <el-input v-model="form.userPhone" />
          </el-form-item>

          <el-form-item label="出生日期" prop="dateBirth">
            <el-date-picker
              v-model="form.dateBirth"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYYMMDD"
              :clearable="false"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          <el-form-item label="公众号openid" prop="gzhOpenid">
            <el-input v-model="form.gzhOpenid" />
          </el-form-item>
          <el-form-item label="微信唯一id" prop="unionId">
            <el-input v-model="form.unionId" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 详情 -->
      <el-dialog v-model="detailDialogVisible" title="游客详情" width="50%">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="人员姓名">{{ form.userName }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ form.userSex === 1 ? '男' : '女' }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">{{ form.userPhone }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">
            {{ useDateFormat(form.dateBirth, 'YYYY-MM-DD').value }}
          </el-descriptions-item>
          <el-descriptions-item label="公众号openid">{{ form.gzhOpenid }}</el-descriptions-item>
          <el-descriptions-item label="微信唯一id">{{ form.unionId }}</el-descriptions-item>
        </el-descriptions>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useDateFormat } from '@vueuse/core'
  import { youkexinxivo } from '@/api/4a/types'
  import {
    scenicTouristUserPageTouristUserUsingPost,
    scenicTouristUserGetTouristUserUsingGet,
    scenicTouristUserUpdateTouristUserUsingPut
  } from '@/api/4a/touristUserController'
  const touristList = ref<youkexinxivo[]>([])
  const total = ref(0)
  const isLoading = ref(true)
  const currentPage = ref(1)
  const searchKeyword = ref('')
  const pageSize = ref(10)
  const sourceFilter = ref('')
  const dialogVisible = ref(false)
  const formRef = ref<FormInstance>()
  const rules = reactive<FormRules>({
    userName: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
    userPhone: [
      { required: false, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ]
  })
  const form = reactive({
    id: undefined,
    userName: '',
    userSex: 0,
    userPhone: '',
    dateBirth: '',
    identityCard: '',
    gzhOpenid: '',
    unionId: '',
    headPortrait: '',
    password: '',
    xcxOpenid: '',
    current: 1,
    size: 10
  })
  // 游客详情
  const detailDialogVisible = ref(false)
  // 请求参数
  const queryParams = computed(() => {
    return {
      current: currentPage.value,
      size: pageSize.value,
      userPhone: searchKeyword.value,
      source: sourceFilter.value
    }
  })
  const disabledDate = (time: Date) => {
    return time.getTime() > Date.now()
  }
  // 获取游客列表
  const getTouristList = async () => {
    isLoading.value = true
    try {
      const res = await scenicTouristUserPageTouristUserUsingPost({
        body: queryParams.value
      })
      if (res.code == 0) {
        touristList.value = res.data?.list || []
        total.value = res.data?.total || 0
      } else {
        ElMessage.error('获取游客列表失败')
      }
    } catch (error: any) {
      console.log(error)
      ElMessage.error('获取游客列表失败')
    } finally {
      isLoading.value = false
    }
  }
  // 处理页码大小变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    getTouristList()
  }

  // 分页切换
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getTouristList()
  }

  // 搜索游客
  const handleSearch = () => {
    currentPage.value = 1
    getTouristList()
  }
  // const showDialog = (type: string, row?: any) => {
  //   dialogVisible.value = true
  //   if (type === 'edit' && row) {
  //     formRef.value?.resetFields();
  //     getTouristDetail(row)
  //   }
  // }
  const showDetailDialog = (row?: any) => {
    detailDialogVisible.value = true
    formRef.value?.resetFields()
    getTouristDetail(row)
  }
  const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
      if (valid) {
        try {
          await scenicTouristUserUpdateTouristUserUsingPut({ body: form })
          ElMessage.success('修改成功')
          formRef.value?.resetFields()
          dialogVisible.value = false
          getTouristList() // 刷新列表
        } catch (error: any) {
          console.log(error)
          ElMessage.error('修改失败')
        }
      }
    })
  }
  // 空状态判断
  const showEmpty = computed(() => {
    return touristList.value.length === 0 && !isLoading.value
  })
  // 详情
  const getTouristDetail = async (row: any) => {
    try {
      const res = await scenicTouristUserGetTouristUserUsingGet({
        params: { id: row.id }
      })
      if (res.code == 0) {
        Object.assign(form, res.data)
      } else {
        ElMessage.error('获取用户详情失败')
      }
    } catch (error) {
      console.log(error)
      ElMessage.error('获取用户详情失败')
    }
  }
  onMounted(() => {
    getTouristList()
  })

  // 监听路由变化
  onActivated(() => {
    getTouristList()
  })
</script>

<style lang="scss" scoped>
  .tourist-list-container {
    min-height: calc(100vh - 121px);
  }

  .filter-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding: 16px;
    // margin-bottom: 20px;
    // background: #fff;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 5%);
    // border: 1px solid var(--art-card-border) !important;
    border-radius: 8px;

    .left-section {
      display: flex;
      gap: 16px;
      align-items: center;

      .search-box {
        width: 300px;

        .search-input {
          width: 100%;
        }
      }
    }

    .filter-box {
      .el-select {
        width: 150px;
      }
    }
  }
  .border-box {
    border-radius: 8px !important;
  }
</style>
